from django.shortcuts import render, redirect
# from users.forms import UserRegForm
from django.http import HttpResponse
from django.contrib.auth import authenticate, get_user_model
from django.contrib.auth import login as user_login, logout as user_logout
from users.forms import User_logforms, User_regforms, User_otherforms
# from shopping.views import Get_user_center_info_html
from django.urls import reverse_lazy


# Create your views here.
# User = get_user_model()

# def register(request):
#     data = UserRegForm(request.POST)
#     if not data.is_valid():
#         return  HttpResponse('数据不合法')
#     res = data.cleaned_data
#     user = User.objects.create_user(**res)
#     # user_login(request, user)
#     url_source = request.META['HTTP_REFERER']
#     return redirect(url_source)

def userlogin(request):
    data = User_logforms(request.POST)
    if not data.is_valid():
        return HttpResponse("数据不合法")
    try:
        res = data.cleaned_data
        user = authenticate(**res)
        user_login(request,user)
    # url_source = request.META["HTTP_REFERER"]
    # user = authenticate(username=request.POST['username'], password=request.POST['password'])
    # login(request,user)       #封装好的函数，用来自己验证，并且向客户端，发送session
    except AttributeError:
        url_source = request.META["HTTP_REFERER"]
        return redirect(url_source)

    url = reverse_lazy("user_center_info")
    return redirect(url)


def userlogout(request):
    user_logout(request)
    url_source = request.META["HTTP_REFERER"]
    return redirect(url_source)


User = get_user_model()
def userregister(request):
    data = User_regforms(request.POST)
    if not data.is_valid():
        return HttpResponse("数据不合法")
    try:
        res = data.cleaned_data
        user = User.objects.create_user(**res)
        user_login(request,user)

    except AttributeError:
        url_source = request.META["HTTP_REFERER"]
        return redirect(url_source)
    url = reverse_lazy("user_center_info")
    return redirect(url)

def useraddother(request):
    comment_pho_adr = dict()
    url_source = request.META.get("HTTP_REFERER")
    if not request.user.id:
        return redirect(url_source)
    phone = request.POST.get("phone", None)
    address = request.POST.get("address", None)
    comment_pho_adr["user"] = request.user.id
    comment_pho_adr["phone"] = phone
    comment_pho_adr["address"] = address
    data = User_otherforms(comment_pho_adr)

    if not data.is_valid():
        return redirect(url_source)

    data.save()

    return redirect(url_source)